package com.teamwork.module03.util;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.Objects;
import java.util.UUID;

public class FileUtils {
    final static Logger log = LoggerFactory.getLogger(FileUtils.class);


    private FileUtils() {}

    /**
     * 下载文件
     *
     * @param path     文件的位置
     * @param fileName 自定义下载文件的名称
     * @param resp     http响应
     * @param req      http请求
     */
    public static void downloadFile(String path, String fileName, HttpServletRequest req, HttpServletResponse resp) {
        String charsetCode = String.valueOf(StandardCharsets.UTF_8);
        try {
            File file = new File(path + "/" + fileName);
            log.info("文件的位置:{}",path+"/"+fileName);
            //中文乱码解决
            String type = req.getHeader("User-Agent").toLowerCase();
            // 字符编码格式
            if (type.indexOf("firefox") > 0 || type.indexOf("chrome") > 0) {
                //谷歌或火狐
                fileName = new String(fileName.getBytes(charsetCode), "iso8859-1");
            } else {
                //IE
                fileName = URLEncoder.encode(fileName, charsetCode);
            }
            // 设置响应的头部信息
            resp.setHeader("content-disposition", "attachment;filename=" + fileName);
            // 设置响应内容的类型
            resp.setContentType(getFileContentType(fileName) + "; charset=" + charsetCode);
            // 设置响应内容的长度
            resp.setContentLength((int) file.length());
            // 输出
            outStream(new FileInputStream(file), resp.getOutputStream());
        } catch (Exception e) {
            log.error("执行文件下载时发生了异常====>{}", e.getMessage());
        }
    }

    /**========================================================*/
    /**
     * 根据文件名判断响应头部类型
     */
    private static String getFileContentType(String name) {
        String result = "";
        String fileType = name.toLowerCase();
        if (fileType.endsWith(".png")) {
            result = "image/png";
        } else if (fileType.endsWith(".gif")) {
            result = "image/gif";
        } else if (fileType.endsWith(".jpg") || fileType.endsWith(".jpeg")) {
            result = "image/jpeg";
        } else if (fileType.endsWith(".svg")) {
            result = "image/svg+xml";
        } else if (fileType.endsWith(".doc")) {
            result = "application/msword";
        } else if (fileType.endsWith(".xls")) {
            result = "application/x-excel";
        } else if (fileType.endsWith(".zip")) {
            result = "application/zip";
        } else if (fileType.endsWith(".pdf")) {
            result = "application/pdf";
        } else {
            result = "application/octet-stream";
        }
        return result;
    }

    /**
     * 基础字节数组输出
     */
    private static void outStream(InputStream is, OutputStream os) {
        try {
            byte[] buffer = new byte[1024];
            int length = -1;
            while ((length = is.read(buffer)) != -1) {
                os.write(buffer, 0, length);
                os.flush();
            }
        } catch (Exception e) {
            log.error("执行 outStream 发生了异常===>{}", e.getMessage());
        } finally {
            try {
                os.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            try {
                is.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
   //根据用户id为名称上传文件
    public static String uploadByUserId(Integer userid, MultipartFile file,String path,String prefix) throws IOException {
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取当前时间
        //String nowtime = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        //获取文件后缀名 例如.png
        assert originalFilename != null;
        String endName = "." + originalFilename.split("\\.")[1];

        String finalName = prefix  + userid + "-" + endName;

        //创建文件架
        File dir = new File(path);
        if(!dir.exists()){
            //不存在
            dir.mkdirs();
        }
        //获取文件对象
        File newFie =new File(path,finalName);

        //先判断是否存在头像，若存在，先删除
        for (File icon : Objects.requireNonNull(dir.listFiles())) {
            if(icon.getName().equals(finalName)){
                icon.delete();
            }
        }
        //上传
        file.transferTo(newFie);
        log.info("用户id:"+userid+" 上传了文件："+finalName+" --至"+path);
        //返回最终上传的文件名称
        return finalName;
    }


    //上传文章内容图片
    public static  String uploadContnetImg(MultipartFile file,String path,String prefix) throws IOException {
        //获取文件原始名称
        String originalFilename = file.getOriginalFilename();
        //获取当前时间
        //String nowtime = new SimpleDateFormat("yyyy-MM-dd-HH-mm-ss").format(new Date());
        //获取文件后缀名 例如.png
        assert originalFilename != null;
        String endName = "." + originalFilename.split("\\.")[1];
        //给个随机名称
        String uuid = UUID.randomUUID().toString();

        String finalName = prefix + uuid + "-" + endName;

        //创建文件架
        File dir = new File(path);
        if (!dir.exists()) {
            //不存在
            dir.mkdirs();
        }
        //获取文件对象
        File newFie = new File(path, finalName);

        //先判断是否存在头像，若存在，先删除
        for (File icon : Objects.requireNonNull(dir.listFiles())) {
            if (icon.getName().equals(finalName)) {
                icon.delete();
            }
        }
        //上传
        file.transferTo(newFie);
        //log.info("用户id:"+userid+" 上传了文件："+finalName+" --至"+path);
        //返回最终上传的文件名称
        return finalName;
    }

    /**
     * 删除指定位置的文件
     * @param name 文件名称
     * @param path 文件路径
     * @return 是否删除
     */
    public static boolean DeleteFile(String name,String path) throws FileNotFoundException {

        File file = new File(path , name);

        if(file==null){
            throw new FileNotFoundException("要删除删除的文件不存在！");
        }

        return file.delete();

    }

    /**
     * 上传文章内容
     * @param content 文章内容
     * @param contentPath 上传路径
     * @param prefix  前缀
     * @return  最终路径
     */
    public static String uploadTxt(String content, String contentPath, String prefix) throws IOException {

        String uuid = UUID.randomUUID().toString();

        String finalName = prefix + uuid + ".html";

        File dir = new File(contentPath);
        if(!dir.exists()){
            dir.mkdirs();
        }

        File newFile = new File(contentPath,finalName);
        //先判断是否存在头像，若存在，先删除
        for (File icon : Objects.requireNonNull(dir.listFiles())) {
            if (icon.getName().equals(finalName)) {
                icon.delete();
            }
        }
        //写入该目录
        FileOutputStream out = new FileOutputStream(newFile);

        //StringBuffer buffer =new StringBuffer(content);

        byte[] bytes = content.getBytes(StandardCharsets.UTF_8);

        out.write(bytes);
        out.flush();

        out.close();


        return finalName;
    }
}
